package com.kangyi.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.*;
import com.kangyi.admin.service.PublicActivityService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.AddPublicActivityDTO;
import com.kangyi.dto.EditPublicActivityDTO;
import com.kangyi.dto.PublicActivityImgDTO;
import com.kangyi.dto.PublicActivityPageDTO;
import com.kangyi.entity.ActivitySignup;
import com.kangyi.entity.InviterInfo;
import com.kangyi.entity.PublicActivity;
import com.kangyi.entity.PublicActivityImg;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.exception.PermissionsException;
import com.kangyi.result.PublicActivityPageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.PublicActivityDetailVO;
import com.kangyi.vo.PublicActivityImgVO;
import com.kangyi.vo.PublicActivityPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Blank
 * @version 1.0
 */
@Service
@Slf4j
public class PublicActivityServiceImpl implements PublicActivityService {

    @Autowired
    private PublicActivityMapper publicActivityMapper;

    @Autowired
    private PublicActivityImageMapper publicActivityImageMapper;

    @Autowired
    private InviterInfoMapper inviterInfoMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ActivitiesSignupMapper activitiesSignupMapper;


    //调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        if (!adminUserVO.getPermissions().equals(1)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }

    @Override
    public PublicActivityPageResult pageQuery(PublicActivityPageDTO publicActivityPageDTO) {
        validateUserPermissions();
        if (publicActivityPageDTO.getStartTime() != null && publicActivityPageDTO.getEndTime() != null && publicActivityPageDTO.getStartTime().isAfter(publicActivityPageDTO.getEndTime())) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }
        PageHelper.startPage(publicActivityPageDTO.getPage(),publicActivityPageDTO.getPageSize());
        Page<PublicActivityPageVO> page = publicActivityMapper.pageQuery(publicActivityPageDTO);
        long total = page.getTotal();
        List<PublicActivityPageVO> result = page.getResult();
        int startingSoon = 0;
        int inProgress = 0;
        int completed = 0;
        for (PublicActivityPageVO vo : result) {
            if (vo.getStatus() == 1) {
                startingSoon++;
            } else if (vo.getStatus() == 2) {
                inProgress++;
            } else if (vo.getStatus() == 3) {
                completed++;
            }
            Integer activityId = vo.getId();
            vo.setTotal(publicActivityMapper.countActivityId(activityId));
        }
        return new PublicActivityPageResult(total,result,startingSoon,inProgress,completed);
    }

    @Override
    @Transactional
    public void addPublicActivity(AddPublicActivityDTO addPublicActivityDTO) {
        validateUserPermissions();

        InviterInfo inviterInfo = new InviterInfo();
        BeanUtil.copyProperties(addPublicActivityDTO.getInviterInfoDTO(), inviterInfo);
        inviterInfoMapper.addInviterInfo(inviterInfo);

        Integer inviterInfoId = inviterInfo.getId();
        if (inviterInfoId == null) {
            throw new DataNotExistException(MessageConstant.DATA_LACK);
        }

        PublicActivity publicActivity = new PublicActivity();
        BeanUtil.copyProperties(addPublicActivityDTO, publicActivity);
        publicActivity.setInviterId(inviterInfoId);
        publicActivity.setStatus(PublicActivity.STARTING_SOON);
        publicActivity.setStartTime(LocalDateTime.of(addPublicActivityDTO.getStartTime(), LocalTime.MIN));
        publicActivity.setEndTime(LocalDateTime.of(addPublicActivityDTO.getEndTime(), LocalTime.MAX));
        publicActivity.setSignupDeadline(LocalDateTime.of(addPublicActivityDTO.getSignupDeadline(), LocalTime.MAX));

        publicActivityMapper.addPublicActivity(publicActivity);

        Integer publicActivityId = publicActivity.getId();

        List<PublicActivityImg> publicActivityImgList = addPublicActivityDTO.getPublicActivityImgDTOList().stream()
                .map(publicActivityImgDTO -> PublicActivityImg.builder()
                        .publicActivityId(publicActivityId)
                        .image(publicActivityImgDTO.getImage())
                        .sort(publicActivityImgDTO.getSort())
                        .build())
                .collect(Collectors.toList());
        publicActivityImageMapper.addBatch(publicActivityImgList);
    }

    @Override
    public PublicActivityDetailVO detailPublicActivity(Integer id) {
        validateUserPermissions();
        PublicActivityDetailVO publicActivityDetailVO = publicActivityMapper.detailPublicActivity(id);
        if (publicActivityDetailVO == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }
        List<PublicActivityImgVO> publicActivityImgVOList = publicActivityImageMapper.selectByPublicActivityId(id);

        publicActivityDetailVO.setPublicActivityImgVOList(publicActivityImgVOList);

        return publicActivityDetailVO;
    }

    @Override
    @Transactional
    public void editPublicActivity(EditPublicActivityDTO editPublicActivityDTO) {
        validateUserPermissions();

        //修改活动基本信息
        PublicActivity publicActivity = new PublicActivity();
        BeanUtil.copyProperties(editPublicActivityDTO, publicActivity);
        publicActivity.setInviterId(editPublicActivityDTO.getInviterInfoVO().getId());
        publicActivity.setStartTime(LocalDateTime.of(editPublicActivityDTO.getStartTime(), LocalTime.MIN));
        publicActivity.setEndTime(LocalDateTime.of(editPublicActivityDTO.getEndTime(), LocalTime.MAX));
        publicActivity.setSignupDeadline(LocalDateTime.of(editPublicActivityDTO.getSignupDeadline(), LocalTime.MAX));
        publicActivityMapper.editPublicActivity(publicActivity);


        Integer id = editPublicActivityDTO.getId();
        if (id == null) {
            throw new DataNotExistException(MessageConstant.DATA_LACK);
        }

        //修改活动图片
        //删除此活动下的所有图片
        publicActivityImageMapper.deleteByPublicActivityId(id);
        //批量新增图片
        List<PublicActivityImg> publicActivityImgList = editPublicActivityDTO.getPublicActivityImgDTOList().stream()
                .map(publicActivityImgDTO ->
                        PublicActivityImg.builder()
                                .publicActivityId(id)
                                .image(publicActivityImgDTO.getImage())
                                .sort(publicActivityImgDTO.getSort())
                                .build()
                ).collect(Collectors.toList());
        publicActivityImageMapper.addBatch(publicActivityImgList);


        InviterInfo inviterInfo = new InviterInfo();
        BeanUtil.copyProperties(editPublicActivityDTO.getInviterInfoVO(), inviterInfo);
        inviterInfoMapper.editInviterInfo(inviterInfo);
    }

    @Override
    @Transactional
    public void deletePublicActivity(List<Integer> ids) {
        validateUserPermissions();
        for (Integer id : ids) {
            try {
                // 检查活动是否存在
                PublicActivity publicActivity = publicActivityMapper.getById(id);
                if (publicActivity == null) {
                    throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
                }

                // 删除活动相关的报名信息
                activitiesSignupMapper.deleteByPublicActivityId(id);

                // 删除活动相关的图片信息
                publicActivityImageMapper.deleteByPublicActivityId(id);

                // 删除公共活动
                publicActivityMapper.deleteById(id);

                // 获取邀请人 ID
                Integer inviterId = publicActivity.getInviterId();
                if (inviterId != null) {
                    // 检查该邀请人是否还有其他关联的公共活动
                    int relatedActivityCount = publicActivityMapper.countByInviterId(inviterId);
                    if (relatedActivityCount == 0) {
                        // 如果没有其他关联活动，删除邀请人信息
                        inviterInfoMapper.deleteById(inviterId);
                    }
                }
            } catch (Exception e) {
                log.error("删除公共活动时出现异常，活动ID: {}", id, e);
                // 手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw e;
            }
        }
    }
}
